<template>
  <div class="starrocks-tables-container">
    
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="header-background">
        <div class="bg-pattern"></div>
        <div class="bg-gradient"></div>
      </div>
      
      
      <div class="page-title">
        <div class="title-icon">
          <div class="icon-container" style="width: 36px; height: 36px; background: linear-gradient(135deg, #9c27b0 0%, #ba68c8 100%); border-radius: 8px; color: white; box-shadow: 0 2px 8px rgba(156, 39, 176, 0.2);">
            <el-icon size="20"><Coin /></el-icon>
            <div class="icon-glow"></div>
          </div>
        </div>
        <div class="title-content">
          <div class="title-main">
            <h1>StarRocks表管理</h1>
            <div class="title-badge">
              <el-icon><Star /></el-icon>
              <span>Data</span>
            </div>
          </div>
          <p class="page-description">
            <el-icon><Monitor /></el-icon>
            管理和监控StarRocks表信息
          </p>
          <div class="title-meta">
            <div class="meta-item">
              <el-icon><Clock /></el-icon>
              <span>实时统计</span>
            </div>
            <div class="meta-item">
              <el-icon><TrendCharts /></el-icon>
              <span>增长分析</span>
            </div>
            <div class="meta-item">
              <el-icon><Setting /></el-icon>
              <span>自动监控</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 统计卡片 -->
      <div class="page-stats">
        <div class="stat-card total">
          <div class="stat-icon">
            <el-icon><Coin /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ totalTables }}</div>
            <div class="stat-label">总表数</div>
            <div class="stat-trend">
              <el-icon><Coin /></el-icon>
              <span>全部</span>
            </div>
          </div>
        </div>
        
        <div class="stat-card monitored">
          <div class="stat-icon">
            <el-icon><Monitor /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ monitoredTables }}</div>
            <div class="stat-label">监控中</div>
            <div class="stat-trend">
              <el-icon><Monitor /></el-icon>
              <span>活跃</span>
            </div>
          </div>
        </div>
        
        <div class="stat-card databases">
          <div class="stat-icon">
            <el-icon><Files /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ totalDatabases }}</div>
            <div class="stat-label">数据库数</div>
            <div class="stat-trend">
              <el-icon><Files /></el-icon>
              <span>连接</span>
            </div>
          </div>
        </div>
        
        <div class="stat-card growth">
          <div class="stat-icon">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ formatNumber(totalDataRows) }}</div>
            <div class="stat-label">总数据行</div>
            <div class="stat-trend">
              <el-icon><TrendCharts /></el-icon>
              <span>增长</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 工具栏 -->
    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-card shadow="hover" class="search-card">
        <template #header>
          <div class="search-header">
            <div class="search-title">
              <el-icon><Search /></el-icon>
              <span>搜索与筛选</span>
            </div>
            <!-- StarRocks实例选择器 -->
            <div class="instance-selector-compact">
              <el-select 
                v-model="selectedConfigId" 
                placeholder="选择实例"
                @change="handleConfigChange"
                size="small"
                style="width: 240px"
              >
                <el-option
                  v-for="config in starrocksConfigs"
                  :key="config.id"
                  :label="`${config.config_name} (${config.host}:${config.port})`"
                  :value="config.id"
                >
                  <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="font-weight: 500;">{{ config.config_name }}</span>
                    <span style="color: #909399; font-size: 12px; margin-left: 20px;">
                      {{ config.host }}:{{ config.port }}
                    </span>
                  </div>
                </el-option>
              </el-select>
              
              <el-tag v-if="currentConfig" type="success" size="small">
                <el-icon><Connection /></el-icon>
                {{ currentConfig.config_name }}
              </el-tag>
            </div>
          </div>
        </template>
        <el-form :model="searchForm" class="search-form">
          <div class="search-form-content">
            <div class="search-form-fields">
              <!-- 主要筛选 - 数据库在前，表名在后，并联动 -->
              <el-form-item label="数据库">
                <el-select
                  v-model="searchForm.database"
                  placeholder="选择数据库"
                  clearable
                  style="width: 150px"
                  @change="handleDatabaseChange"
                >
                  <el-option label="全部" value="" />
                  <el-option
                    v-for="db in databases"
                    :key="db.database_name"
                    :label="`${db.database_name} (${db.table_count})`"
                    :value="db.database_name"
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item label="表名">
                <el-autocomplete
                  v-model="searchForm.searchText"
                  :fetch-suggestions="queryTableSuggestions"
                  placeholder="输入或点击选择表"
                  clearable
                  style="width: 250px"
                  :trigger-on-focus="true"
                  :debounce="300"
                  @select="handleTableSelect"
                  @focus="handleTableInputFocus"
                >
                  <template #default="{ item }">
                    <div class="table-suggestion-item">
                      <el-icon><Coin /></el-icon>
                      <div class="suggestion-content">
                        <div class="suggestion-name">{{ item.table_name }}</div>
                        <div class="suggestion-meta">
                          <span class="suggestion-db">{{ item.database_name }}</span>
                          <span class="suggestion-comment">{{ item.table_comment || '无注释' }}</span>
                        </div>
                      </div>
                    </div>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </div>
            
            <div class="search-form-actions">
              <el-button 
                type="info" 
                @click="advancedSearchExpanded = !advancedSearchExpanded" 
                class="advanced-btn"
                plain
              >
                <el-icon>
                  <component :is="advancedSearchExpanded ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                高级筛选
              </el-button>
              <el-button type="primary" @click="handleSearch" class="search-btn">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button type="warning" @click="handleReset" class="reset-btn">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
              <el-button 
                type="success" 
                @click="quickActionsExpanded = !quickActionsExpanded" 
                class="quick-actions-btn"
                plain
              >
                <el-icon>
                  <component :is="quickActionsExpanded ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                快捷操作
              </el-button>
            </div>
          </div>
          
          <!-- 高级筛选折叠区域 -->
          <transition name="advanced-filter">
            <div v-show="advancedSearchExpanded" class="advanced-filter-section">
              <div class="advanced-filter-fields">
                <el-form-item label="监控状态">
                  <el-select
                    v-model="searchForm.monitorStatus"
                    placeholder="选择监控状态"
                    clearable
                    style="width: 140px"
                  >
                    <el-option label="全部" value="" />
                    <el-option label="监控中" value="true" />
                    <el-option label="未监控" value="false" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="存储介质">
                  <el-select
                    v-model="searchForm.storageMedium"
                    placeholder="选择存储介质"
                    clearable
                    style="width: 120px"
                  >
                    <el-option label="全部" value="" />
                    <el-option label="SSD" value="SSD" />
                    <el-option label="HDD" value="HDD" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="分区状态">
                  <el-select
                    v-model="searchForm.partitionStatus"
                    placeholder="选择分区状态"
                    clearable
                    style="width: 120px"
                  >
                    <el-option label="全部" value="" />
                    <el-option label="分区表" value="true" />
                    <el-option label="非分区表" value="false" />
                  </el-select>
                </el-form-item>
              </div>
            </div>
          </transition>
          
          <!-- 快捷操作折叠区域 -->
          <transition name="quick-actions">
            <div v-show="quickActionsExpanded" class="quick-actions-section">
              <div class="quick-actions-toolbar">
                <div class="toolbar-left">
                  <!-- 选中表格时显示徽章 -->
                  <template v-if="selectedTables.length > 0">
                    <div class="selected-info-inline">
                      <el-icon class="selected-icon"><Select /></el-icon>
                      <span>已选择 <strong>{{ selectedTables.length }}</strong> 个表</span>
                    </div>
                    
                    <el-divider direction="vertical" />
                  </template>
                  
                  <!-- 未选中时显示通用操作 -->
                  <template v-else>
                    <div class="button-group">
                      <el-button type="primary" @click="oneClickUpdate" :loading="updating" class="btn-one-click">
                        <el-icon><Refresh /></el-icon>
                        一键更新
                      </el-button>
                      
                      <el-button @click="fetchLatestTables" :loading="fetchingLatest" class="btn-fetch-latest">
                        <el-icon><Download /></el-icon>
                        获取最新表
                      </el-button>
                    </div>
                    
                    <el-divider direction="vertical" />
                  </template>
                  
                  <!-- 批量操作按钮（无论是否选中都显示） -->
                  <div class="button-group">
                    <el-button @click="showDataStatistics" class="btn-statistics">
                      <el-icon><TrendCharts /></el-icon>
                      数据统计
                    </el-button>
                    
                    <el-button @click="showUpdateSchema" class="btn-schema">
                      <el-icon><Files /></el-icon>
                      更新表结构
                    </el-button>
                  </div>
                  
                  <el-divider direction="vertical" />
                  
                  <!-- 监控管理（无论是否选中都显示） -->
                  <div class="button-group">
                    <el-button @click="showMonitorManagement" class="btn-monitor">
                      <el-icon><Monitor /></el-icon>
                      监控管理
                    </el-button>
                  </div>
                  
                  <!-- 监控配置（仅未选中时显示） -->
                  <template v-if="selectedTables.length === 0">
                    <div class="button-group">
                      <el-button @click="showMonitorConfig = true" class="btn-config">
                        <el-icon><Setting /></el-icon>
                        监控配置
                      </el-button>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </transition>
        </el-form>
      </el-card>
    </div>


    <!-- 表格 -->
    <div class="table-section">
      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="table-header">
            <div class="table-title">
              <el-icon><List /></el-icon>
              <span>表列表</span>
            </div>
            <div class="table-header-actions">
              <el-button type="success" @click="fetchTables" class="refresh-btn" :loading="loading" size="small">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <div class="table-info">
                <!-- 合并的分页信息控制 -->
                <div class="pagination-control-wrapper" @click="paginationExpanded = !paginationExpanded">
                  <span class="page-count">本页 {{ tables.length }} 条</span>
                  <div class="divider"></div>
                  <span class="pagination-info">{{ currentPage }}/{{ Math.ceil(totalCount / pageSize) }}</span>
                  <el-icon class="pagination-icon" :class="{ 'expanded': paginationExpanded }">
                    <ArrowDown />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </template>
        <div class="table-container">
          <el-table
            ref="tableRef"
            v-loading="loading"
            :data="tables"
            :row-key="row => row.id"
            @selection-change="handleSelectionChange"
            @sort-change="handleSortChange"
            :default-sort="{ prop: sortField, order: sortOrder === 'asc' ? 'ascending' : 'descending' }"
            height="600"
            style="width: 100%"
          >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="database_name" label="数据库" width="80">
          <template #default="{ row }">
            <el-tag size="small" type="info">{{ row.database_name }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="table_name" label="表名" width="350">
          <template #default="{ row }">
            <div class="table-name-cell-new">
              <div class="table-name-wrapper">
                <span class="table-name-text">{{ row.table_name }}</span>
                <el-tooltip content="复制表名" placement="top">
                  <el-button 
                    type="info"
                    size="small" 
                    @click.stop="handleCopyTableName(row.table_name)" 
                    circle
                    class="table-copy-btn"
                  >
                    <el-icon><DocumentCopy /></el-icon>
                  </el-button>
                </el-tooltip>
              </div>
              <div class="table-badges">
                <el-tag v-if="row.is_partitioned" size="small" type="warning">分区</el-tag>
                <el-tag v-if="row.storage_medium === 'SSD'" size="small" type="success">SSD</el-tag>
                <el-tag v-if="row.storage_medium === 'HDD'" size="small" type="info">HDD</el-tag>
                <el-tag v-if="row.key_type" size="small" type="primary">{{ row.key_type }}</el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="table_comment" label="表注释" min-width="200" show-overflow-tooltip />
        
        <el-table-column prop="total_rows" label="数据行数" width="120" sortable="custom">
          <template #default="{ row }">
            <span class="number-cell">{{ formatNumber(row.total_rows) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="data_length" label="数据大小" width="120" sortable="custom">
          <template #default="{ row }">
            <span class="number-cell">{{ formatBytes(row.data_length) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="previous_increment_rows" label="上次增量" width="110" sortable="custom">
          <template #default="{ row }">
            <span :class="['increment-cell', row.previous_increment_rows > 0 ? 'positive' : row.previous_increment_rows < 0 ? 'negative' : 'zero']">
              {{ formatIncrement(row.previous_increment_rows) }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="current_increment_rows" label="当前增量" width="110" sortable="custom">
          <template #default="{ row }">
            <span :class="['increment-cell', row.current_increment_rows > 0 ? 'positive' : row.current_increment_rows < 0 ? 'negative' : 'zero']">
              {{ formatIncrement(row.current_increment_rows) }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="total_increment_rows" label="总增量" width="120" sortable="custom">
          <template #default="{ row }">
            <div class="increment-display">
              <span :class="['increment-cell', row.total_increment_rows > 0 ? 'positive' : row.total_increment_rows < 0 ? 'negative' : 'zero']">
                {{ formatIncrement(row.total_increment_rows) }}
              </span>
              <el-tag 
                :type="getIncrementTagType(row.last_stat_type)" 
                size="mini" 
                class="increment-tag"
              >
                {{ getIncrementLabel(row.last_stat_type) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="monitor_enabled" label="监控状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.monitor_enabled"
              @change="toggleMonitor(row)"
              :loading="row.switching"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="last_stat_time" label="最后统计" width="150" sortable="custom">
          <template #default="{ row }">
            <span v-if="row.last_stat_time" class="time-cell">
              {{ formatTime(row.last_stat_time) }}
            </span>
            <span v-else class="no-data">未统计</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-tooltip content="查看详情" placement="top">
                <el-button 
                  type="primary"
                  size="small" 
                  @click="viewDetails(row)" 
                  circle
                >
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
              
              <el-tooltip content="统计表数据" placement="top">
                <el-button 
                  type="success"
                  size="small" 
                  @click="countTable(row)" 
                  :loading="row.counting"
                  circle
                >
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </el-tooltip>
              
              <el-tooltip content="同步结构" placement="top">
                <el-button 
                  type="warning"
                  size="small" 
                  @click="syncTable(row)" 
                  circle
                >
                  <el-icon><RefreshRight /></el-icon>
                </el-button>
              </el-tooltip>
              
              <el-tooltip content="生成查询语句" placement="top">
                <el-button 
                  type="info"
                  size="small" 
                  @click="generateTableQuery(row)" 
                  circle
                >
                  <el-icon><Document /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
          </el-table>
        </div>
        
        <!-- 分页折叠区域 -->
        <transition name="pagination-slide">
          <div v-show="paginationExpanded" class="pagination-section">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="totalCount"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="fetchTables"
              @current-change="fetchTables"
              background
            />
          </div>
        </transition>
      </el-card>
    </div>

    <!-- 表详情对话框 -->
    <el-dialog
      v-model="showTableDetail"
      width="80%"
      top="5vh"
      :close-on-click-modal="false"
      class="unified-dialog table-detail-dialog-wrapper"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-primary">
            <el-icon><Coin /></el-icon>
          </div>
          <div class="header-content">
            <h3>表详情</h3>
            <p>{{ currentTable?.database_name }}.{{ currentTable?.table_name }}</p>
          </div>
        </div>
      </template>
      <TableDetailDialog
        v-if="showTableDetail && currentTable"
        :table="currentTable"
        :config-id="selectedConfigId"
        @close="showTableDetail = false"
      />
    </el-dialog>

    <!-- 监控配置对话框 -->
    <el-dialog
      v-model="showMonitorConfig"
      width="800px"
      :close-on-click-modal="false"
      class="unified-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-primary">
            <el-icon><Setting /></el-icon>
          </div>
          <div class="header-content">
            <h3>监控配置</h3>
            <p>配置表数据监控和定时任务</p>
          </div>
        </div>
      </template>
      
      <MonitorConfigDialog
        v-if="showMonitorConfig"
        @close="showMonitorConfig = false"
        @updated="loadMonitorStatus"
      />
    </el-dialog>

    <!-- 批量同步对话框 -->
    <el-dialog
      v-model="showBatchSync"
      width="600px"
      :close-on-click-modal="false"
      class="unified-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-primary">
            <el-icon><RefreshRight /></el-icon>
          </div>
          <div class="header-content">
            <h3>批量同步表结构</h3>
            <p>同步选中的{{ selectedTables.length }}个表的结构信息</p>
          </div>
        </div>
      </template>
      
      <div class="dialog-content">
        <div v-if="batchSyncProgress.running" class="sync-progress">
          <el-progress
            :percentage="batchSyncProgress.percentage"
            :status="batchSyncProgress.status"
          />
          <p style="margin-top: 16px; text-align: center;">{{ batchSyncProgress.message }}</p>
        </div>
        <el-alert
          v-else
          title="确认同步"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>确认要同步选中的 <strong>{{ selectedTables.length }}</strong> 个表的结构信息吗？</p>
          </template>
        </el-alert>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showBatchSync = false" :disabled="batchSyncProgress.running">取消</el-button>
          <el-button 
            type="primary" 
            @click="executeBatchSync" 
            :loading="batchSyncProgress.running"
          >
            <el-icon><Check /></el-icon>
            确认同步
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- SQL查询生成器对话框 -->
    <el-dialog
      v-model="showQueryGenerator"
      width="800px"
      :close-on-click-modal="false"
      class="unified-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-primary">
            <el-icon><DocumentAdd /></el-icon>
          </div>
          <div class="header-content">
            <h3>SQL查询生成器</h3>
            <p>根据选择的字段自动生成SQL查询语句</p>
          </div>
        </div>
      </template>
      <div v-if="queryGeneratorData.loading" class="loading-container">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>正在生成查询语句...</span>
      </div>
      
      <div v-else>
        <!-- 表信息 -->
        <div class="query-table-info">
          <h4>
            <el-icon><Coin /></el-icon>
            表信息: {{ queryGeneratorData.currentTable?.database_name }}.{{ queryGeneratorData.currentTable?.table_name }}
          </h4>
          <p>字段数量: {{ queryGeneratorData.fields.length }}</p>
        </div>

        <!-- 生成的查询语句 -->
        <div class="query-result">
          <div class="query-header">
            <h4>
              <el-icon><Document /></el-icon>
              生成的查询语句:
            </h4>
            <div class="query-actions">
              <el-button 
                size="small" 
                @click="toggleSqlFormat"
              >
                <el-icon><component :is="queryGeneratorData.isFormatted ? RefreshLeft : Check" /></el-icon>
                {{ queryGeneratorData.isFormatted ? '恢复原样' : '美化SQL' }}
              </el-button>
              <el-button 
                size="small" 
                type="primary" 
                @click="copyQueryToClipboard"
              >
                <el-icon><CopyDocument /></el-icon>
                复制
              </el-button>
            </div>
          </div>
          
          <el-input
            v-model="displayQuery"
            type="textarea"
            :rows="queryGeneratorData.isFormatted ? 20 : 12"
            readonly
            class="query-textarea"
          />
        </div>

        <!-- 字段列表 -->
        <div class="query-fields">
          <h4>
            <el-icon><List /></el-icon>
            字段列表 ({{ queryGeneratorData.fieldDetails.length }}):
          </h4>
          <div class="fields-list">
            <div 
              v-for="(field, index) in queryGeneratorData.fieldDetails" 
              :key="field.field_name || index"
              class="field-item"
            >
              <div class="field-info">
                <div class="field-name">
                  <el-icon><Document /></el-icon>
                  <strong>{{ field.field_name }}</strong>
                </div>
                <div class="field-details">
                  <el-tag 
                    :type="getFieldTypeColor(field.data_type)" 
                    size="small"
                    class="field-type"
                  >
                    {{ field.data_type }}
                  </el-tag>
                  <span v-if="field.nullable === 'YES'" class="field-nullable">
                    <el-tag type="info" size="small">可空</el-tag>
                  </span>
                  <span v-if="field.default_value" class="field-default">
                    默认值: <code>{{ field.default_value }}</code>
                  </span>
                </div>
                <div v-if="field.comment" class="field-comment">
                  <el-icon><ChatLineRound /></el-icon>
                  {{ field.comment }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showQueryGenerator = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 数据统计对话框 -->
    <el-dialog
      v-model="showDataStatisticsDialog"
      width="600px"
      :close-on-click-modal="false"
      class="unified-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-success">
            <el-icon><DataAnalysis /></el-icon>
          </div>
          <div class="header-content">
            <h3>数据统计</h3>
            <p>查看表的数据统计信息</p>
          </div>
        </div>
      </template>
      <div class="dialog-content">
        <!-- 数据库选择 -->
        <el-form-item label="选择数据库:">
          <el-select 
            v-model="dialogData.dataStatistics.selectedDatabase"
            placeholder="选择数据库（默认全部）"
            clearable
            style="width: 100%"
            :disabled="dialogData.dataStatistics.selectedTables.length > 0"
            popper-class="batch-dialog-select-popper"
            :teleported="true"
          >
            <el-option label="全部数据库" value="" />
            <el-option
              v-for="db in databases"
              :key="db.database_name"
              :label="db.database_name"
              :value="db.database_name"
            />
          </el-select>
        </el-form-item>

        <!-- 统计模式选择 -->
        <el-form-item label="统计模式:">
          <el-radio-group v-model="dialogData.dataStatistics.statisticsMode">
            <el-radio value="information_schema">信息模式（快速）</el-radio>
            <el-radio value="count_query">COUNT查询（准确）</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 选中表提示 -->
        <div v-if="dialogData.dataStatistics.selectedTables.length > 0" class="selected-tables-info">
          <el-alert
            :title="`已选中 ${dialogData.dataStatistics.selectedTables.length} 个表进行统计`"
            type="info"
            :closable="false"
          />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showDataStatisticsDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="executeDataStatistics"
          :loading="dialogData.dataStatistics.loading"
        >
          开始统计
        </el-button>
      </template>
    </el-dialog>

    <!-- 监控管理对话框 -->
    <el-dialog
      v-model="showMonitorManagementDialog"
      width="600px"
      :close-on-click-modal="false"
      class="unified-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-warning">
            <el-icon><Monitor /></el-icon>
          </div>
          <div class="header-content">
            <h3>监控管理</h3>
            <p>批量启用或停用表监控</p>
          </div>
        </div>
      </template>
      <div class="dialog-content">
        <!-- 数据库选择 -->
        <el-form-item label="选择数据库:">
          <el-select 
            v-model="dialogData.monitorManagement.selectedDatabase"
            placeholder="选择数据库（默认全部）"
            clearable
            style="width: 100%"
            :disabled="dialogData.monitorManagement.selectedTables.length > 0"
            popper-class="batch-dialog-select-popper"
            :teleported="true"
          >
            <el-option label="全部数据库" value="" />
            <el-option
              v-for="db in databases"
              :key="db.database_name"
              :label="db.database_name"
              :value="db.database_name"
            />
          </el-select>
        </el-form-item>

        <!-- 选中表提示 -->
        <div v-if="dialogData.monitorManagement.selectedTables.length > 0" class="selected-tables-info">
          <el-alert
            :title="`已选中 ${dialogData.monitorManagement.selectedTables.length} 个表进行监控管理`"
            type="info"
            :closable="false"
          />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showMonitorManagementDialog = false">取消</el-button>
        <el-button 
          type="success" 
          @click="executeMonitorAction(true)"
          :loading="dialogData.monitorManagement.loading"
        >
          启用监控
        </el-button>
        <el-button 
          type="warning" 
          @click="executeMonitorAction(false)"
          :loading="dialogData.monitorManagement.loading"
        >
          停止监控
        </el-button>
      </template>
    </el-dialog>

    <!-- 更新表结构对话框 -->
    <el-dialog
      v-model="showUpdateSchemaDialog"
      width="600px"
      :close-on-click-modal="false"
      class="unified-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-primary">
            <el-icon><RefreshRight /></el-icon>
          </div>
          <div class="header-content">
            <h3>更新表结构</h3>
            <p>批量更新表的结构信息</p>
          </div>
        </div>
      </template>
      <div class="dialog-content">
        <!-- 数据库选择 -->
        <el-form-item label="选择数据库:">
          <el-select 
            v-model="dialogData.updateSchema.selectedDatabase"
            placeholder="选择数据库（默认全部）"
            clearable
            style="width: 100%"
            :disabled="dialogData.updateSchema.selectedTables.length > 0"
            popper-class="batch-dialog-select-popper"
            :teleported="true"
          >
            <el-option label="全部数据库" value="" />
            <el-option
              v-for="db in databases"
              :key="db.database_name"
              :label="db.database_name"
              :value="db.database_name"
            />
          </el-select>
        </el-form-item>

        <!-- 选中表提示 -->
        <div v-if="dialogData.updateSchema.selectedTables.length > 0" class="selected-tables-info">
          <el-alert
            :title="`已选中 ${dialogData.updateSchema.selectedTables.length} 个表进行结构更新`"
            type="info"
            :closable="false"
          />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showUpdateSchemaDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="executeUpdateSchema"
          :loading="dialogData.updateSchema.loading"
        >
          更新结构
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 进度对话框 -->
    <ProgressDialog
      v-model="progressDialog.visible"
      :title="progressDialog.title"
      :current-step="progressDialog.currentStep"
      :description="progressDialog.description"
      :steps="progressDialog.steps"
      :current-step-index="progressDialog.currentStepIndex"
      :progress-percentage="progressDialog.progressPercentage"
      :show-progress="progressDialog.showProgress"
      :stats="progressDialog.stats"
      :can-cancel="progressDialog.canCancel"
      :is-completed="progressDialog.isCompleted"
      :cancelling="progressDialog.cancelling"
      @cancel="handleProgressCancel"
      @close="handleProgressClose"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { storeToRefs } from 'pinia'
import { useAppStore } from '@/stores/app'
import {
  Coin, Star, Monitor, Clock, TrendCharts, Setting, Files,
  Refresh, RefreshRight, RefreshLeft, Download, Search, View, ArrowDown, ArrowUp, Document, 
  Loading, CopyDocument, List, Close, ChatLineRound, Connection, Minus, DocumentCopy, Select, Check
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import api from '@/utils/api'
import { logger } from '@/utils/logger'
import { copyToClipboard as copyText } from '@/utils/clipboard'
import taskNotifier from '@/utils/taskNotifier'
import TableDetailDialog from './components/TableDetailDialog.vue'
import MonitorConfigDialog from './components/MonitorConfigDialog.vue'
import ProgressDialog from './components/ProgressDialog.vue'

const router = useRouter()
const appStore = useAppStore()
const { sidebarCollapsed } = storeToRefs(appStore)

// StarRocks配置相关
const starrocksConfigs = ref([])
const selectedConfigId = ref(null)
const currentConfig = computed(() => {
  return starrocksConfigs.value.find(c => c.id === selectedConfigId.value)
})

// 响应式数据
const loading = ref(false)
const updating = ref(false)
const fetchingLatest = ref(false)
const tables = ref([])
const databases = ref([])
const selectedTables = ref([])
const currentTable = ref(null)
const isInitializing = ref(true) // 添加初始化标志

// 进度对话框数据
const progressDialog = reactive({
  visible: false,
  title: '正在处理',
  currentStep: '正在执行操作...',
  description: '请稍候，操作正在进行中',
  steps: [],
  currentStepIndex: 0,
  progressPercentage: 0,
  showProgress: false,
  stats: null,
  canCancel: false,
  isCompleted: false,
  cancelling: false
})

// 全局统计数据
const overviewStats = ref({
  total_tables: 0,
  monitored_tables: 0,
  total_databases: 0,
  total_data_rows: 0
})

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const totalCount = ref(0)
const paginationExpanded = ref(false) // 分页折叠控制

// 搜索和过滤
const advancedSearchExpanded = ref(false) // 高级筛选折叠控制
const quickActionsExpanded = ref(false) // 快捷操作折叠控制
const searchForm = reactive({
  searchText: '',
  database: '',  // 默认选择全部数据库
  monitorStatus: '',
  storageMedium: '',
  partitionStatus: ''
})

// 排序 - 默认按总增量从高到低（三增量设计）
const sortField = ref('total_increment_rows')
const sortOrder = ref('desc')

// 对话框状态
const showTableDetail = ref(false)
const showMonitorConfig = ref(false)
const showQueryGenerator = ref(false)
const showDataStatisticsDialog = ref(false)
const showMonitorManagementDialog = ref(false)
const showUpdateSchemaDialog = ref(false)
const showBatchSync = ref(false)

// SQL查询生成器状态
const queryGeneratorData = reactive({
  currentTable: null,
  loading: false,
  generatedQuery: '', // 原始查询（单行）
  formattedQuery: '', // 格式化查询（多行）
  isFormatted: false, // 是否显示格式化版本
  fields: [],
  fieldDetails: [] // 详细的字段信息
})

// 对话框数据状态
const dialogData = reactive({
  // 数据统计对话框
  dataStatistics: {
    selectedDatabase: '',
    selectedTables: [],
    statisticsMode: 'information_schema', // information_schema, count_query
    loading: false
  },
  // 监控管理对话框
  monitorManagement: {
    selectedDatabase: '',
    selectedTables: [],
    loading: false
  },
  // 更新表结构对话框
  updateSchema: {
    selectedDatabase: '',
    selectedTables: [],
    loading: false
  }
})

// 批量同步进度
const batchSyncProgress = reactive({
  running: false,
  percentage: 0,
  message: '',
  status: ''
})

// 统计数据
// 计算属性 - 使用全局统计数据
const totalTables = computed(() => overviewStats.value.total_tables)
const monitoredTables = computed(() => overviewStats.value.monitored_tables)
const totalDatabases = computed(() => overviewStats.value.total_databases)
const totalDataRows = computed(() => overviewStats.value.total_data_rows)

// SQL 显示查询 - 根据格式化状态返回对应的查询
const displayQuery = computed(() => {
  return queryGeneratorData.isFormatted 
    ? queryGeneratorData.formattedQuery 
    : queryGeneratorData.generatedQuery
})

// 格式化函数 - 使用中文单位（支持负数）
const formatNumber = (num) => {
  if (!num) return '0'
  
  // 处理负数：保留符号，用绝对值计算单位
  const isNegative = num < 0
  const absNum = Math.abs(num)
  const sign = isNegative ? '-' : ''
  
  if (absNum >= 1e8) {
    const value = absNum / 1e8
    return sign + (value >= 10 ? Math.round(value) + '亿' : value.toFixed(1) + '亿')
  }
  if (absNum >= 1e4) {
    const value = absNum / 1e4
    return sign + (value >= 10 ? Math.round(value) + '万' : value.toFixed(1) + '万')
  }
  return num.toLocaleString('zh-CN')
}

const formatBytes = (bytes) => {
  if (!bytes) return '0 B'
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i]
}

const formatIncrement = (increment) => {
  if (!increment) return '0'
  const sign = increment > 0 ? '+' : ''
  return sign + formatNumber(increment)
}

const formatTime = (timeStr) => {
  if (!timeStr) return ''
  try {
    const date = new Date(timeStr)
    const now = new Date()
    
    // 如果是今天，显示时分秒
    if (date.toDateString() === now.toDateString()) {
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit',
        second: '2-digit'
      })
    }
    
    // 如果是昨天，显示"昨天 HH:mm:ss"
    const yesterday = new Date(now)
    yesterday.setDate(yesterday.getDate() - 1)
    if (date.toDateString() === yesterday.toDateString()) {
      return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit',
        second: '2-digit'
      })
    }
    
    // 超过昨天，显示月日时分
    return date.toLocaleDateString('zh-CN', { 
      month: '2-digit', 
      day: '2-digit',
      hour: '2-digit', 
      minute: '2-digit'
    })
  } catch {
    return timeStr
  }
}

// 新的按钮处理函数（使用任务通知系统）
const oneClickUpdate = async () => {
  if (!selectedConfigId.value) {
    ElMessage.warning('请先选择StarRocks实例')
    return
  }
  
  // 记录任务开始
  taskNotifier.saveTaskStart({
    name: '一键更新',
    type: 'one_click_update',
    configId: selectedConfigId.value
  })
  
  try {
    updating.value = true
    
    ElMessage({
      message: '✨ 任务已在后台运行，完成后将自动通知',
      type: 'success',
      duration: 3000,
      showClose: true,
      grouping: true
    })
    
    // 调用后端API - 超时30分钟
    const response = await api.post('/starrocks-tables/one-click-update', {
      config_id: selectedConfigId.value
    }, {
      timeout: 1800000  // 30分钟
    })
    
    if (response.data.success) {
      // 保存任务结果
      taskNotifier.saveTaskResult('一键更新', response.data, true)
      
      // 立即显示通知
      taskNotifier.checkAndNotify()
      
      // 刷新页面数据
      await Promise.all([fetchDatabases(), fetchTables(), fetchOverviewStats()])
    } else {
      taskNotifier.saveTaskResult('一键更新', response.data.error, false)
      taskNotifier.checkAndNotify()
    }
    
  } catch (error) {
    logger.error('一键更新失败:', error)
    taskNotifier.saveTaskResult('一键更新', error.message, false)
    taskNotifier.checkAndNotify()
  } finally {
    updating.value = false
  }
}

const fetchLatestTables = async () => {
  if (!selectedConfigId.value) {
    ElMessage.warning('请先选择StarRocks实例')
    return
  }
  
  // 记录任务开始
  taskNotifier.saveTaskStart({
    name: '获取最新表',
    type: 'fetch_latest',
    configId: selectedConfigId.value
  })
  
  try {
    fetchingLatest.value = true
    
    ElMessage({
      message: '✨ 任务已在后台运行，完成后将自动通知',
      type: 'success',
      duration: 3000,
      showClose: true,
      grouping: true
    })
    
    // 调用后端API - 超时30分钟
    const response = await api.post('/starrocks-tables/fetch-latest', {
      config_id: selectedConfigId.value
    }, {
      timeout: 1800000  // 30分钟
    })
    
    if (response.data.success) {
      // 保存任务结果
      taskNotifier.saveTaskResult('获取最新表', response.data.data, true)
      
      // 立即显示通知
      taskNotifier.checkAndNotify()
      
      // 刷新页面数据
      await fetchTables()
    } else {
      taskNotifier.saveTaskResult('获取最新表', response.data.error, false)
      taskNotifier.checkAndNotify()
    }
    
  } catch (error) {
    logger.error('获取最新表失败:', error)
    taskNotifier.saveTaskResult('获取最新表', error.message, false)
    taskNotifier.checkAndNotify()
  } finally {
    fetchingLatest.value = false
  }
}

const showDataStatistics = () => {
  dialogData.dataStatistics.selectedDatabase = ''  // 默认选择全部数据库
  dialogData.dataStatistics.selectedTables = []
  dialogData.dataStatistics.statisticsMode = 'information_schema'
  
  // 如果有选中的表，直接使用选中的表
  if (selectedTables.value.length > 0) {
    dialogData.dataStatistics.selectedTables = [...selectedTables.value]
  }
  
  showDataStatisticsDialog.value = true
}

const showMonitorManagement = () => {
  logger.info('打开监控管理对话框，当前数据库列表:', databases.value)
  dialogData.monitorManagement.selectedDatabase = ''  // 默认选择全部数据库
  dialogData.monitorManagement.selectedTables = []
  
  // 如果有选中的表，直接使用选中的表
  if (selectedTables.value.length > 0) {
    dialogData.monitorManagement.selectedTables = [...selectedTables.value]
  }
  
  showMonitorManagementDialog.value = true
}

const showUpdateSchema = () => {
  dialogData.updateSchema.selectedDatabase = ''  // 默认选择全部数据库
  dialogData.updateSchema.selectedTables = []
  
  // 如果有选中的表，直接使用选中的表
  if (selectedTables.value.length > 0) {
    dialogData.updateSchema.selectedTables = [...selectedTables.value]
  }
  
  showUpdateSchemaDialog.value = true
}

// 对话框执行函数
const executeDataStatistics = async () => {
  if (!selectedConfigId.value) {
    ElMessage.warning('请先选择StarRocks实例')
    return
  }
  
  try {
    // 验证选择：选中表模式 或 数据库选择模式
    const hasSelectedTables = dialogData.dataStatistics.selectedTables && dialogData.dataStatistics.selectedTables.length > 0
    const hasSelectedDatabase = dialogData.dataStatistics.selectedDatabase !== null && dialogData.dataStatistics.selectedDatabase !== undefined
    
    if (hasSelectedTables) {
      logger.info('数据统计：选中表模式，处理选中的表')
    } else if (hasSelectedDatabase) {
      const dbName = dialogData.dataStatistics.selectedDatabase || '全部数据库'
      logger.info(`数据统计：数据库选择模式，处理 ${dbName}`)
    } else {
      ElMessage.warning('请选择要统计的表或选择数据库')
      return
    }
    
    // 记录任务开始
    taskNotifier.saveTaskStart({
      name: '数据统计',
      type: 'batch_statistics',
      configId: selectedConfigId.value
    })
    
    // 立即关闭对话框
    showDataStatisticsDialog.value = false
    
    // 显示后台任务提示
    ElMessage({
      message: '✨ 任务已在后台运行，完成后将自动通知',
      type: 'success',
      duration: 3000,
      showClose: true,
      grouping: true
    })
    
    dialogData.dataStatistics.loading = true
    
    // 构建要操作的表ID列表
    let tableIds = []
    
    if (hasSelectedTables) {
      // 如果用户选择了具体的表，使用选中的表
      tableIds = dialogData.dataStatistics.selectedTables.map(t => t.id)
    } else if (hasSelectedDatabase) {
      // 如果用户选择了数据库，调用API获取该数据库的所有表
      if (dialogData.dataStatistics.selectedDatabase === '') {
        // 选择了"全部数据库"，不传database参数，后端会处理所有表
        tableIds = []
      } else {
        // 选择了具体数据库，调用API获取该数据库的表
        try {
          const response = await api.get('/starrocks-tables/tables', {
            params: {
              config_id: selectedConfigId.value,
              database: dialogData.dataStatistics.selectedDatabase,
              pageSize: 1000 // 获取足够多的表
            }
          })
          if (response.data.success) {
            tableIds = response.data.data.tables.map(t => t.id)
            if (tableIds.length === 0) {
              ElMessage.warning(`数据库 ${dialogData.dataStatistics.selectedDatabase} 中没有找到表`)
              return
            }
          }
        } catch (error) {
          logger.error('获取数据库表列表失败:', error)
          ElMessage.error('获取数据库表列表失败')
          return
        }
      }
    }
    
    const requestData = {
      config_id: selectedConfigId.value,
      database: dialogData.dataStatistics.selectedDatabase,
      method: dialogData.dataStatistics.statisticsMode,
      tables: tableIds
    }
    
    // 批量统计 - 超时时间根据模式设置
    const timeout = dialogData.dataStatistics.statisticsMode === 'count_query' 
      ? 3600000  // COUNT模式：1小时
      : 1800000  // information_schema模式：30分钟
    
    const response = await api.post('/starrocks-tables/statistics/execute', requestData, {
      timeout: timeout
    })
    
    if (response.data.success) {
      const result = response.data.data
      
      // 保存任务结果
      taskNotifier.saveTaskResult('数据统计', result, true)
      
      // 立即显示通知
      taskNotifier.checkAndNotify()
      
      // 刷新页面数据
      await Promise.all([fetchTables(), fetchOverviewStats()])
    } else {
      taskNotifier.saveTaskResult('数据统计', response.data.error, false)
      taskNotifier.checkAndNotify()
    }
  } catch (error) {
    logger.error('数据统计失败:', error)
    taskNotifier.saveTaskResult('数据统计', error.message, false)
    taskNotifier.checkAndNotify()
  } finally {
    dialogData.dataStatistics.loading = false
  }
}

const executeMonitorAction = async (enable) => {
  if (!selectedConfigId.value) {
    ElMessage.warning('请先选择StarRocks实例')
    return
  }
  
  try {
    // 检查是否选择了表或数据库
    const hasSelectedTables = dialogData.monitorManagement.selectedTables && dialogData.monitorManagement.selectedTables.length > 0
    const hasSelectedDatabase = dialogData.monitorManagement.selectedDatabase !== null && dialogData.monitorManagement.selectedDatabase !== undefined
    
    if (!hasSelectedTables && !hasSelectedDatabase) {
      ElMessage.warning('请先选择要操作的表或选择数据库')
      return
    }
    
    dialogData.monitorManagement.loading = true
    
    // 显示进度提示
    const progressMessage = ElMessage({
      message: `正在${enable ? '启用' : '禁用'}监控，请稍候...`,
      type: 'info',
      duration: 0, // 不自动关闭
      showClose: false
    })
    
    // 构建要操作的表ID列表
    let tableIds = []
    
    if (hasSelectedTables) {
      // 如果用户选择了具体的表，使用选中的表
      tableIds = dialogData.monitorManagement.selectedTables.map(t => t.id)
    } else if (hasSelectedDatabase) {
      // 如果用户选择了数据库，调用API获取该数据库的所有表
      if (dialogData.monitorManagement.selectedDatabase === '') {
        // 选择了"全部数据库"，不传database参数，后端会处理所有表
        tableIds = []
      } else {
        // 选择了具体数据库，调用API获取该数据库的表
        try {
          const response = await api.get('/starrocks-tables/tables', {
            params: {
              config_id: selectedConfigId.value,
              database: dialogData.monitorManagement.selectedDatabase,
              pageSize: 1000 // 获取足够多的表
            }
          })
          if (response.data.success) {
            tableIds = response.data.data.tables.map(t => t.id)
            if (tableIds.length === 0) {
              progressMessage.close() // 确保关闭进度提示
              ElMessage.warning(`数据库 ${dialogData.monitorManagement.selectedDatabase} 中没有找到表`)
              return
            }
          }
        } catch (error) {
          progressMessage.close() // 确保关闭进度提示
          logger.error('获取数据库表列表失败:', error)
          ElMessage.error('获取数据库表列表失败')
          return
        }
      }
    }
    
    const requestData = {
      config_id: selectedConfigId.value,
      database: dialogData.monitorManagement.selectedDatabase,
      monitor_enabled: enable,
      tables: tableIds
    }
    
    const response = await api.post('/starrocks-tables/monitor/batch-toggle', requestData)
    
    // 关闭进度提示
    progressMessage.close()
    
    if (response.data.success) {
      const result = response.data.data
      
      // 优化消息显示
      if (result.processed_tables === 0) {
        ElMessage.warning(result.message || '没有选择要操作的表')
      } else {
        ElMessage.success(
          `监控${enable ? '启用' : '停止'}完成：处理 ${result.processed_tables} 个表，` +
          `成功 ${result.success_tables} 个，失败 ${result.failed_tables} 个`
        )
      }
      
      showMonitorManagementDialog.value = false
      await Promise.all([fetchTables(), fetchOverviewStats()])
    }
  } catch (error) {
    // 关闭进度提示
    progressMessage.close()
    logger.error('监控管理失败:', error)
    ElMessage.error('监控管理失败')
  } finally {
    dialogData.monitorManagement.loading = false
  }
}

const executeUpdateSchema = async () => {
  if (!selectedConfigId.value) {
    ElMessage.warning('请先选择StarRocks实例')
    return
  }
  
  try {
    // 检查是否选择了表或数据库
    const hasSelectedTables = dialogData.updateSchema.selectedTables && dialogData.updateSchema.selectedTables.length > 0
    const hasSelectedDatabase = dialogData.updateSchema.selectedDatabase !== null && dialogData.updateSchema.selectedDatabase !== undefined
    
    if (!hasSelectedTables && !hasSelectedDatabase) {
      ElMessage.warning('请先选择要更新的表或选择数据库')
      return
    }
    
    // 记录任务开始
    taskNotifier.saveTaskStart({
      name: '更新表结构',
      type: 'schema_update',
      configId: selectedConfigId.value
    })
    
    // 立即关闭对话框
    showUpdateSchemaDialog.value = false
    
    // 显示后台任务提示
    ElMessage({
      message: '✨ 任务已在后台运行，完成后将自动通知',
      type: 'success',
      duration: 3000,
      showClose: true,
      grouping: true
    })
    
    dialogData.updateSchema.loading = true
    
    // 构建要操作的表ID列表
    let tableIds = []
    
    if (hasSelectedTables) {
      // 如果用户选择了具体的表，使用选中的表
      tableIds = dialogData.updateSchema.selectedTables.map(t => t.id)
    } else if (hasSelectedDatabase) {
      // 如果用户选择了数据库，调用API获取该数据库的所有表
      if (dialogData.updateSchema.selectedDatabase === '') {
        // 选择了"全部数据库"，不传database参数，后端会处理所有表
        tableIds = []
      } else {
        // 选择了具体数据库，调用API获取该数据库的表
        try {
          const response = await api.get('/starrocks-tables/tables', {
            params: {
              config_id: selectedConfigId.value,
              database: dialogData.updateSchema.selectedDatabase,
              pageSize: 1000 // 获取足够多的表
            }
          })
          if (response.data.success) {
            tableIds = response.data.data.tables.map(t => t.id)
            if (tableIds.length === 0) {
              ElMessage.warning(`数据库 ${dialogData.updateSchema.selectedDatabase} 中没有找到表`)
              return
            }
          }
        } catch (error) {
          logger.error('获取数据库表列表失败:', error)
          ElMessage.error('获取数据库表列表失败')
          return
        }
      }
    }
    
    const requestData = {
      config_id: selectedConfigId.value,
      database: dialogData.updateSchema.selectedDatabase,
      tables: tableIds
    }
    
    // 更新表结构 - 超时20分钟
    const response = await api.post('/starrocks-tables/schema/batch-update', requestData, {
      timeout: 1200000  // 20分钟
    })
    
    if (response.data.success) {
      const result = response.data.data
      
      // 保存任务结果
      taskNotifier.saveTaskResult('更新表结构', result, true)
      
      // 立即显示通知
      taskNotifier.checkAndNotify()
      
      // 刷新表列表
      await fetchTables()
    } else {
      taskNotifier.saveTaskResult('更新表结构', response.data.error, false)
      taskNotifier.checkAndNotify()
    }
  } catch (error) {
    logger.error('表结构更新失败:', error)
    taskNotifier.saveTaskResult('更新表结构', error.message, false)
    taskNotifier.checkAndNotify()
  } finally {
    dialogData.updateSchema.loading = false
  }
}

// 辅助函数（已废弃，保留以兼容旧代码）
const syncAllDatabases = async () => {
  if (!selectedConfigId.value) {
    ElMessage.warning('请先选择StarRocks实例')
    return
  }
  for (const db of databases.value) {
    await api.post(`/starrocks-tables/databases/${db.database_name}/sync`, {
      config_id: selectedConfigId.value
    })
  }
}

const collectAllTablesData = async (method) => {
  if (!selectedConfigId.value) {
    ElMessage.warning('请先选择StarRocks实例')
    return
  }
  await api.post('/starrocks-tables/stats/collect', { 
    config_id: selectedConfigId.value,
    method 
  })
}

const updateAllTablesSchema = async () => {
  if (!selectedConfigId.value) {
    ElMessage.warning('请先选择StarRocks实例')
    return
  }
  for (const db of databases.value) {
    await api.post(`/starrocks-tables/databases/${db.database_name}/sync`, {
      config_id: selectedConfigId.value
    })
  }
}

// API调用
const fetchOverviewStats = async () => {
  if (!selectedConfigId.value) {
    return
  }
  
  try {
    const response = await api.get('/starrocks-tables/stats/overview', {
      params: { config_id: selectedConfigId.value }
    })
    if (response.data.success) {
      overviewStats.value = response.data.data
    }
  } catch (error) {
    logger.error('获取总体统计失败:', error)
    ElMessage.error('获取总体统计失败')
  }
}

const fetchDatabases = async () => {
  if (!selectedConfigId.value) {
    return
  }
  
  try {
    logger.info('开始获取数据库列表...')
    const response = await api.get('/starrocks-tables/databases', {
      params: { config_id: selectedConfigId.value }
    })
    logger.info('数据库API响应:', response.data)
    if (response.data.success) {
      databases.value = response.data.data.databases
      logger.info('数据库列表已更新:', databases.value)
    }
  } catch (error) {
    logger.error('获取数据库列表失败:', error)
    ElMessage.error('获取数据库列表失败')
  }
}

const fetchTables = async () => {
  if (!selectedConfigId.value) {
    ElMessage.warning('请先选择StarRocks实例')
    return
  }
  
  loading.value = true
  try {
    const params = {
      config_id: selectedConfigId.value,
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    if (searchForm.searchText) params.search = searchForm.searchText
    if (searchForm.database) params.database = searchForm.database
    if (searchForm.monitorStatus) params.monitor_enabled = searchForm.monitorStatus
    if (searchForm.storageMedium) params.storage_medium = searchForm.storageMedium
    if (searchForm.partitionStatus) params.is_partitioned = searchForm.partitionStatus
    if (sortField.value) {
      params.sort = sortField.value
      params.order = sortOrder.value
    }
    
    const response = await api.get('/starrocks-tables/tables', { params })
    if (response.data.success) {
      tables.value = response.data.data.tables.map(table => ({
        ...table,
        monitor_enabled: Boolean(table.monitor_enabled), // 转换为布尔值
        switching: false,
        counting: false
      }))
      totalCount.value = response.data.data.pagination.total
      
      // 记录表列表加载信息（仅开发环境）
      logger.debug('表列表加载完成', {
        count: tables.value.length,
        sort: params.sort,
        order: params.order
      })
    }
  } catch (error) {
    logger.error('获取表列表失败:', error)
    ElMessage.error('获取表列表失败')
  } finally {
    loading.value = false
  }
}

const syncAllTables = async () => {
  if (!selectedConfigId.value) {
    ElMessage.warning('请先选择StarRocks实例')
    return
  }
  
  if (databases.value.length === 0) {
    ElMessage.warning('请先获取数据库列表')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确认要同步所有 ${databases.value.length} 个数据库的表结构吗？`,
      '批量同步确认',
      { type: 'warning' }
    )
    
    syncing.value = true
    let successCount = 0
    
    for (const db of databases.value) {
      try {
        const response = await api.post(`/starrocks-tables/databases/${db.database_name}/sync`, {
          config_id: selectedConfigId.value
        })
        if (response.data.success) {
          successCount++
        }
      } catch (error) {
        logger.error(`同步数据库 ${db.database_name} 失败:`, error)
      }
    }
    
    ElMessage.success(`同步完成，成功 ${successCount}/${databases.value.length} 个数据库`)
    await fetchTables()
    
  } catch (error) {
    if (error !== 'cancel') {
      logger.error('批量同步失败:', error)
      ElMessage.error('批量同步失败')
    }
  } finally {
    syncing.value = false
  }
}


const toggleMonitor = async (table) => {
  // 防止页面初始化时触发
  if (isInitializing.value) {
    logger.info('页面初始化中，跳过监控状态切换...')
    return
  }
  
  table.switching = true
  try {
    const response = await api.put(`/starrocks-tables/tables/${table.id}/monitor`, {
      monitor_enabled: table.monitor_enabled
    })
    
    if (response.data.success) {
      ElMessage.success(`${table.monitor_enabled ? '启用' : '禁用'}监控成功`)
      // 刷新全局统计
      await fetchOverviewStats()
    }
  } catch (error) {
    logger.error('切换监控状态失败:', error)
    ElMessage.error('切换监控状态失败')
    // 回滚状态
    table.monitor_enabled = !table.monitor_enabled
  } finally {
    table.switching = false
  }
}

const countTable = async (table) => {
  if (!selectedConfigId.value) {
    ElMessage.warning('请先选择StarRocks实例')
    return
  }
  
  // 大表提示（超过5000万行）
  if (table.total_rows > 50000000) {
    ElMessage.warning({
      message: `表数据量较大(${formatNumber(table.total_rows)}行)，COUNT统计可能需要1-3分钟，请耐心等待...`,
      duration: 5000,
      grouping: true
    })
  }
  
  table.counting = true
  try {
    // 单表COUNT - 超时10分钟
    const response = await api.post(`/starrocks-tables/tables/${table.id}/count`, {
      config_id: selectedConfigId.value
    }, {
      timeout: 600000  // 10分钟
    })
    if (response.data.success || response.data) {
      const result = response.data.data || response.data
      
      // 获取更新后的增量数据
      const detailResponse = await api.get(`/starrocks-tables/tables/${table.id}`)
      if (detailResponse.data.success) {
        const latestData = detailResponse.data.data.table_info
        // 纯增量设计：只需要current_increment
      }
      
      ElMessage.success(
        `COUNT统计完成：${formatNumber(result.total_rows)} 行｜` +
        `上次${formatIncrement(result.previous_increment)}，` +
        `当前${formatIncrement(result.current_increment)}，` +
        `总计${formatIncrement(result.total_increment)}｜` +
        `耗时${result.collection_duration_ms}ms`
      )
      
      // 只更新当前行的数据，不刷新整个列表（避免跳页）
      try {
        if (detailResponse.data.success) {
          const latestData = detailResponse.data.data.table_info
          // 更新当前行的显示数据（三增量设计 - 上次/当前/总计）
          table.total_rows = latestData.total_rows || latestData.latest_total_rows
          table.data_length = latestData.data_length || latestData.latest_data_length
          table.index_length = latestData.index_length || latestData.latest_index_length
          table.last_stat_time = latestData.last_stat_time
          // 三增量字段
          table.previous_increment_rows = latestData.previous_increment_rows || 0
          table.current_increment_rows = latestData.current_increment_rows || 0
          table.total_increment_rows = latestData.total_increment_rows || 0
          table.last_stat_type = latestData.last_stat_type || 'manual'
          // 当天基准
          table.today_start_total_rows = latestData.today_start_total_rows || 0
          table.today_start_date = latestData.today_start_date
        }
      } catch (error) {
        logger.warn('更新表数据失败，将刷新列表:', error)
        // 如果单独更新失败，再刷新整个列表
        await fetchTables()
      }
      
      // 刷新全局统计
      await fetchOverviewStats()
    }
  } catch (error) {
    logger.error('COUNT统计失败:', error)
    ElMessage.error('COUNT统计失败: ' + (error.response?.data?.error || error.message))
  } finally {
    table.counting = false
  }
}

const viewDetails = (table) => {
  currentTable.value = table
  showTableDetail.value = true
}

// 批量查看详情（查看第一个表的详情）
const batchViewDetails = () => {
  if (selectedTables.value.length === 0) return
  if (selectedTables.value.length === 1) {
    viewDetails(selectedTables.value[0])
  } else {
    // 直接查看第一个表，用户已知道自己在做什么，不需要提示
    viewDetails(selectedTables.value[0])
  }
}

// 批量统计数据
const batchCountTables = async () => {
  if (selectedTables.value.length === 0) return
  
  try {
    await ElMessageBox.confirm(
      `确认要统计选中的 ${selectedTables.value.length} 个表吗？`,
      '批量统计确认',
      { type: 'warning' }
    )
    
    let successCount = 0
    for (const table of selectedTables.value) {
      try {
        table.counting = true
        await countTable(table)
        successCount++
      } catch (error) {
        logger.error(`统计表 ${table.table_name} 失败:`, error)
      } finally {
        table.counting = false
      }
    }
    
    ElMessage.success(`批量统计完成：成功 ${successCount}/${selectedTables.value.length} 个`)
    
  } catch (error) {
    if (error !== 'cancel') {
      logger.error('批量统计失败:', error)
      ElMessage.error('批量统计失败')
    }
  }
}

// 批量同步结构
const batchSyncTables = async () => {
  if (selectedTables.value.length === 0) return
  
  try {
    await ElMessageBox.confirm(
      `确认要同步选中的 ${selectedTables.value.length} 个表的结构吗？`,
      '批量同步确认',
      { type: 'warning' }
    )
    
    let successCount = 0
    for (const table of selectedTables.value) {
      try {
        await syncTable(table)
        successCount++
      } catch (error) {
        logger.error(`同步表 ${table.table_name} 失败:`, error)
      }
    }
    
    ElMessage.success(`批量同步完成：成功 ${successCount}/${selectedTables.value.length} 个`)
    
  } catch (error) {
    if (error !== 'cancel') {
      logger.error('批量同步失败:', error)
      ElMessage.error('批量同步失败')
    }
  }
}

// 批量生成SQL（生成第一个表的SQL）
const batchGenerateQuery = () => {
  if (selectedTables.value.length === 0) return
  if (selectedTables.value.length === 1) {
    generateTableQuery(selectedTables.value[0])
  } else {
    // 直接生成第一个表的SQL，不需要提示
    generateTableQuery(selectedTables.value[0])
  }
}

// 复制表名功能 - 使用统一工具
const handleCopyTableName = async (tableName) => {
  if (!tableName) {
    ElMessage.warning('表名为空，无法复制')
    return
  }
  await copyText(tableName, '表名', false)
  ElMessage.success({
    message: `表名已复制: ${tableName}`,
    duration: 2000
  })
}

// 旧版本保留用于兼容
const copyTableName = async (tableName) => {
  await copyText(tableName, '表名')
}

// 表名自动补全功能（联动数据库，点击即显示）
const queryTableSuggestions = async (queryString, callback) => {
  if (!selectedConfigId.value) {
    callback([])
    return
  }
  
  try {
    // 调用API搜索表名（联动当前选择的数据库）
    const params = {
      config_id: selectedConfigId.value,
      pageSize: 20,  // 限制返回20个建议
      sort: 'total_increment_rows',  // 按总增量排序
      order: 'desc'
    }
    
    // 如果有输入，使用搜索
    if (queryString && queryString.trim() !== '') {
      params.search = queryString
    }
    
    // 联动：如果选择了数据库，只搜索该数据库的表
    if (searchForm.database) {
      params.database = searchForm.database
    }
    
    const response = await api.get('/starrocks-tables/tables', { params })
    
    if (response.data.success) {
      const suggestions = response.data.data.tables.map(table => ({
        value: table.table_name,  // 用于显示和选择
        table_name: table.table_name,
        table_comment: table.table_comment,
        database_name: table.database_name,
        total_rows: table.total_rows
      }))
      callback(suggestions)
    } else {
      callback([])
    }
  } catch (error) {
    logger.error('搜索表名失败:', error)
    callback([])
  }
}

const handleTableInputFocus = () => {
  // 聚焦时的处理（trigger-on-focus会自动触发queryTableSuggestions）
  logger.info('表名输入框聚焦，显示建议列表')
}

const handleTableSelect = (item) => {
  // 选中表名后，自动填充到搜索框并执行搜索
  searchForm.searchText = item.table_name
  handleSearch()
}

// 数据库切换事件（联动清空表名）
const handleDatabaseChange = () => {
  // 切换数据库时，清空表名搜索（避免跨库搜索混乱）
  if (searchForm.database) {
    logger.info(`数据库切换为: ${searchForm.database}`)
  }
  // 自动执行搜索
  handleSearch()
}

// 事件处理
const handleSearch = () => {
  currentPage.value = 1
  fetchTables()
}

const handleReset = () => {
  searchForm.searchText = ''
  searchForm.database = ''  // 重置为全部数据库
  searchForm.monitorStatus = ''
  searchForm.storageMedium = ''
  searchForm.partitionStatus = ''
  currentPage.value = 1
  fetchTables()
}

const handleSelectionChange = (selection) => {
  selectedTables.value = selection
}

const handleSortChange = ({ prop, order }) => {
  // 排序变化处理
  if (!order) {
    // 取消排序，恢复默认排序（三增量设计）
    sortField.value = 'total_increment_rows'
    sortOrder.value = 'desc'
  } else {
    sortField.value = prop
    sortOrder.value = order === 'ascending' ? 'asc' : 'desc'
  }
  
  fetchTables()
}

const handleBatchAction = async (command) => {
  if (selectedTables.value.length === 0) {
    ElMessage.warning('请先选择要操作的表')
    return
  }
  
  try {
    switch (command) {
      case 'enable-monitor':
        await batchToggleMonitor(true)
        break
      case 'disable-monitor':
        await batchToggleMonitor(false)
        break
      case 'sync-selected':
        showBatchSync.value = true
        break
    }
  } catch (error) {
    logger.error('批量操作失败:', error)
    ElMessage.error('批量操作失败')
  }
}

const batchToggleMonitor = async (enabled) => {
  try {
    await ElMessageBox.confirm(
      `确认要${enabled ? '启用' : '禁用'} ${selectedTables.value.length} 个表的监控吗？`,
      '批量操作确认',
      { type: 'warning' }
    )
    
    let successCount = 0
    for (const table of selectedTables.value) {
      try {
        await api.put(`/starrocks-tables/tables/${table.id}/monitor`, {
          monitor_enabled: enabled
        })
        table.monitor_enabled = enabled
        successCount++
      } catch (error) {
        logger.error(`操作表 ${table.table_name} 失败:`, error)
      }
    }
    
    ElMessage.success(`批量操作完成：成功 ${successCount}/${selectedTables.value.length} 个`)
    
  } catch (error) {
    if (error !== 'cancel') {
      throw error
    }
  }
}

const executeBatchSync = async () => {
  batchSyncProgress.running = true
  batchSyncProgress.percentage = 0
  batchSyncProgress.status = ''
  
  try {
    // 按数据库分组
    const dbGroups = {}
    selectedTables.value.forEach(table => {
      if (!dbGroups[table.database_name]) {
        dbGroups[table.database_name] = []
      }
      dbGroups[table.database_name].push(table)
    })
    
    const totalDbs = Object.keys(dbGroups).length
    let completedDbs = 0
    
    for (const [dbName, tables] of Object.entries(dbGroups)) {
      batchSyncProgress.message = `正在同步数据库: ${dbName} (${tables.length} 个表)`
      
      try {
        await api.post(`/starrocks-tables/databases/${dbName}/sync`, {
          config_id: selectedConfigId.value
        })
        completedDbs++
        batchSyncProgress.percentage = Math.round((completedDbs / totalDbs) * 100)
      } catch (error) {
        logger.error(`同步数据库 ${dbName} 失败:`, error)
      }
    }
    
    batchSyncProgress.status = 'success'
    batchSyncProgress.message = '批量同步完成'
    
    ElMessage.success(`批量同步完成：${completedDbs}/${totalDbs} 个数据库`)
    await fetchTables()
    
    setTimeout(() => {
      showBatchSync.value = false
      batchSyncProgress.running = false
    }, 1500)
    
  } catch (error) {
    batchSyncProgress.status = 'exception'
    batchSyncProgress.message = '批量同步失败'
    logger.error('批量同步失败:', error)
    ElMessage.error('批量同步失败')
  }
}

// 同步表结构
const syncTable = async (row) => {
  if (!selectedConfigId.value) {
    ElMessage.warning('请先选择StarRocks实例')
    return
  }
  
  try {
    await api.post(`/starrocks-tables/databases/${row.database_name}/sync`, {
      config_id: selectedConfigId.value
    })
    ElMessage.success('表结构同步成功')
    await fetchTables()
  } catch (error) {
    logger.error('同步表结构失败:', error)
    ElMessage.error('同步表结构失败')
  }
}

// 格式化 SQL 查询
const formatSql = (sql) => {
  if (!sql) return ''
  
  // 提取 SELECT、FROM、LIMIT 等部分
  const selectMatch = sql.match(/SELECT\s+(.*?)\s+FROM/is)
  const fromMatch = sql.match(/FROM\s+([\w.]+)/i)
  const limitMatch = sql.match(/LIMIT\s+(\d+)/i)
  
  if (!selectMatch || !fromMatch) return sql
  
  // 格式化字段列表
  const fields = selectMatch[1]
    .split(',')
    .map(field => field.trim())
    .filter(field => field.length > 0)
  
  // 构建格式化的 SQL
  let formattedSql = 'SELECT\n'
  formattedSql += fields.map((field, index) => {
    return '\t' + field + (index < fields.length - 1 ? ',' : '')
  }).join('\n')
  formattedSql += '\nFROM\n\t' + fromMatch[1]
  
  if (limitMatch) {
    formattedSql += '\nLIMIT ' + limitMatch[1]
  }
  
  formattedSql += ';'
  
  return formattedSql
}

// 切换 SQL 格式
const toggleSqlFormat = () => {
  queryGeneratorData.isFormatted = !queryGeneratorData.isFormatted
}

// 生成表查询语句
const generateTableQuery = async (table) => {
  try {
    queryGeneratorData.loading = true
    queryGeneratorData.currentTable = table
    
    // 获取表字段信息
    logger.info(`正在获取表 ${table.database_name}.${table.table_name} 的字段信息`)
    const response = await api.get(`/starrocks-tables/sql-parser/table-fields/${table.database_name}/${table.table_name}`)
    
    if (response.data.success) {
      const data = response.data.data
      // 如果后端返回的是详细字段信息对象数组
      if (data.fields && data.fields.length > 0 && typeof data.fields[0] === 'object') {
        queryGeneratorData.fieldDetails = data.fields
        queryGeneratorData.fields = data.fields.map(field => field.field_name)
      } else {
        // 如果返回的是字段名数组，创建简单的字段详情
        queryGeneratorData.fields = data.fields || []
        queryGeneratorData.fieldDetails = (data.fields || []).map(field => ({
          field_name: field,
          data_type: 'unknown',
          nullable: 'YES',
          default_value: null,
          comment: ''
        }))
      }
      
      // 生成SELECT查询语句
      const queryResponse = await api.post('/starrocks-tables/sql-parser/generate', {
        table_name: table.table_name,
        fields: queryGeneratorData.fields,
        schema_name: table.database_name
      })
      
      if (queryResponse.data.success) {
        const queryData = queryResponse.data.data
        queryGeneratorData.generatedQuery = queryData.select_query
        queryGeneratorData.formattedQuery = formatSql(queryData.select_query)
        queryGeneratorData.isFormatted = false // 默认显示原始格式
        showQueryGenerator.value = true
        logger.info(`成功生成查询语句，包含 ${queryData.field_count} 个字段`)
      } else {
        ElMessage.error('生成查询语句失败: ' + queryResponse.data.error)
      }
    } else {
      ElMessage.error('获取表字段失败: ' + response.data.error)
    }
  } catch (error) {
    logger.error('生成查询语句失败:', error)
    ElMessage.error('生成查询语句失败')
  } finally {
    queryGeneratorData.loading = false
  }
}

// 复制查询语句到剪贴板 - 使用统一工具
const copyQueryToClipboard = async () => {
  const textToCopy = queryGeneratorData.isFormatted 
    ? queryGeneratorData.formattedQuery 
    : queryGeneratorData.generatedQuery
  await copyText(textToCopy, '查询语句')
}

const loadMonitorStatus = async () => {
  // 重新加载监控状态等信息
  await Promise.all([fetchTables(), fetchOverviewStats()])
}

// 生命周期
// 加载StarRocks配置列表
const loadStarRocksConfigs = async () => {
  try {
    const response = await api.get('/starrocks-tables/configs')
    if (response.data.success) {
      starrocksConfigs.value = response.data.data
      
      // 从localStorage恢复上次选择的配置
      const savedConfigId = localStorage.getItem('starrocks_config_id')
      if (savedConfigId && starrocksConfigs.value.find(c => c.id == savedConfigId)) {
        selectedConfigId.value = parseInt(savedConfigId)
      } else {
        // 默认选择STARROCKS(65) - config_id=57
        const defaultConfig = starrocksConfigs.value.find(c => c.config_name === 'STARROCKS(65)')
        if (defaultConfig) {
          selectedConfigId.value = defaultConfig.id
        } else if (starrocksConfigs.value.length > 0) {
          // 如果没找到65，选择第一个配置
          selectedConfigId.value = starrocksConfigs.value[0].id
        }
      }
      
      logger.info('加载StarRocks配置成功', { count: starrocksConfigs.value.length, selectedId: selectedConfigId.value })
    }
  } catch (error) {
    logger.error('加载StarRocks配置失败:', error)
    ElMessage.error('加载StarRocks配置失败')
  }
}

// 配置切换事件
const handleConfigChange = async (configId) => {
  logger.info('切换StarRocks配置', { configId })
  // 保存到localStorage
  localStorage.setItem('starrocks_config_id', configId)
  
  // 重新加载所有数据
  try {
    await Promise.all([
      fetchDatabases(),
      fetchTables(),
      fetchOverviewStats()
    ])
    ElMessage.success(`已切换到: ${currentConfig.value.config_name}`)
  } catch (error) {
    logger.error('切换配置后加载数据失败:', error)
    ElMessage.error('切换配置失败')
  }
}

// 监听选中表格的变化，自动展开/折叠快捷操作
watch(() => selectedTables.value.length, (newLength) => {
  if (newLength > 0) {
    // 有选中表格时，自动展开快捷操作
    quickActionsExpanded.value = true
  } else {
    // 取消选中时，自动折叠快捷操作
    quickActionsExpanded.value = false
  }
})

onMounted(async () => {
  try {
    // 检查是否有待通知的任务结果（刷新页面后显示）
    taskNotifier.checkAndNotify()
    
    // 请求浏览器通知权限
    taskNotifier.requestPermission()
    
    // 清空选中状态，防止从其他页面返回时显示旧的快捷操作栏
    selectedTables.value = []
    
    // 先加载配置列表
    await loadStarRocksConfigs()
    
    // 如果已选择配置，则加载数据
    if (selectedConfigId.value) {
      await Promise.all([
        fetchDatabases(),
        fetchTables(),
        fetchOverviewStats()
      ])
    }
  } finally {
    // 页面初始化完成，允许监控状态切换
    setTimeout(() => {
      isInitializing.value = false
      logger.info('页面初始化完成，监控状态切换已启用')
    }, 1000) // 延迟1秒确保所有数据绑定完成
  }
})

// 进度对话框处理函数
const showProgressDialog = (config) => {
  Object.assign(progressDialog, {
    visible: true,
    isCompleted: false,
    cancelling: false,
    stats: null,
    ...config
  })
}

const updateProgressDialog = (updates) => {
  Object.assign(progressDialog, updates)
}

const completeProgressDialog = (stats) => {
  progressDialog.isCompleted = true
  progressDialog.stats = stats
  progressDialog.currentStep = '操作完成'
  progressDialog.description = '所有操作已成功完成'
}

const handleProgressCancel = () => {
  progressDialog.cancelling = true
  // 这里可以添加取消操作的逻辑
  setTimeout(() => {
    progressDialog.visible = false
    progressDialog.cancelling = false
  }, 1000)
}

const handleProgressClose = () => {
  progressDialog.visible = false
}

// 根据字段类型返回标签颜色
const getFieldTypeColor = (dataType) => {
  if (!dataType) return 'info'
  
  const type = dataType.toLowerCase()
  
  // 数值类型
  if (type.includes('int') || type.includes('bigint') || type.includes('tinyint') || 
      type.includes('smallint') || type.includes('decimal') || type.includes('double') || 
      type.includes('float')) {
    return 'success'
  }
  
  // 字符串类型
  if (type.includes('varchar') || type.includes('char') || type.includes('text') || 
      type.includes('string')) {
    return 'primary'
  }
  
  // 日期时间类型
  if (type.includes('date') || type.includes('time') || type.includes('timestamp')) {
    return 'warning'
  }
  
  // JSON类型
  if (type.includes('json')) {
    return 'danger'
  }
  
  return 'info'
}

// 纯增量设计：智能标签函数
const getIncrementLabel = (statType) => {
  switch (statType) {
    case 'manual':
      return '实时'
    case 'hourly':
      return '小时'
    default:
      return '增量'
  }
}

const getIncrementTagType = (statType) => {
  switch (statType) {
    case 'manual':
      return 'warning'  // 橙色 - 手动操作
    case 'hourly':
      return 'success'  // 绿色 - 定时任务
    default:
      return 'info'     // 蓝色 - 默认
  }
}
</script>

<style scoped>
/* 页面样式 */
.starrocks-tables-container {
  padding: 0;
}

.page-header {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 24px;
  border-radius: 12px;
  overflow: hidden;
  background: white;
  color: #303133;
  min-height: 120px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* StarRocks实例选择器 - 搜索标题右侧 */
.instance-selector-compact {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0.05;
}

.bg-pattern {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(circle at 20% 50%, rgba(64, 158, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(103, 194, 58, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 40% 80%, rgba(245, 108, 108, 0.1) 0%, transparent 50%);
}

.bg-gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.02) 0%, rgba(103, 194, 58, 0.02) 100%);
}

.page-title {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  gap: 24px;
  flex: 1;
}

.title-icon {
  position: relative;
}

.page-header .title-icon .icon-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px !important;
  height: 36px !important;
  border-radius: 8px !important;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(156, 39, 176, 0.2) !important;
}

.page-header .title-icon .icon-container:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 16px rgba(156, 39, 176, 0.3) !important;
}

.page-header .title-icon .icon-glow {
  position: absolute;
  top: -4px;
  left: -4px;
  right: -4px;
  bottom: -4px;
  background: linear-gradient(45deg, rgba(156, 39, 176, 0.2), rgba(186, 104, 200, 0.3));
  border-radius: 12px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.page-header .title-icon .icon-container:hover .icon-glow {
  opacity: 1;
}


.title-content {
  flex: 1;
}

.title-main {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.title-main h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  letter-spacing: -0.3px;
}

.title-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 12px;
  background: linear-gradient(135deg, #9c27b0 0%, #ba68c8 100%);
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  color: white;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  box-shadow: 0 2px 8px rgba(156, 39, 176, 0.25);
}

.page-description {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.5;
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-description .el-icon {
  font-size: 16px;
  color: #909399;
}

.title-meta {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #909399;
  font-size: 12px;
  font-weight: 500;
}

.page-stats {
  position: relative;
  z-index: 1;
  display: flex;
  gap: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  min-width: 120px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.stat-card:hover {
  background: #fff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.stat-card:hover::before {
  opacity: 1;
}

.stat-icon {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 6px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.stat-card.total .stat-icon {
  background: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

.stat-card.monitored .stat-icon {
  background: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

.stat-card.databases .stat-icon {
  background: rgba(230, 162, 60, 0.1);
  color: #e6a23c;
}

.stat-card.growth .stat-icon {
  background: rgba(156, 39, 176, 0.1);
  color: #9c27b0;
}

.stat-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
}

.stat-number {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 10px;
  color: #909399;
  font-weight: 500;
}

/* 工具栏样式 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.toolbar-left {
  display: flex;
  gap: 12px;
  align-items: center;
}

.toolbar-right {
  display: flex;
  gap: 12px;
  align-items: center;
}


/* 选中信息内联显示 */
.selected-info-inline {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 6px;
  color: white;
  font-size: 14px;
  white-space: nowrap;
}

.selected-info-inline .selected-icon {
  font-size: 16px;
  animation: pulse 2s infinite;
}

.selected-info-inline strong {
  font-size: 16px;
  font-weight: 600;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
}

/* 表格区域 */
.table-section {
  margin-bottom: 24px;
}

.table-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.table-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-title .el-icon {
  color: #409eff;
}

.table-header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.refresh-btn {
  border-radius: 6px;
  font-weight: 500;
}

/* 合并的分页控制容器 */
.pagination-control-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background: rgba(64, 158, 255, 0.08);
  border: 1px solid rgba(64, 158, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  font-size: 12px;
  height: 24px;
}

.pagination-control-wrapper:hover {
  background: rgba(64, 158, 255, 0.12);
  border-color: rgba(64, 158, 255, 0.3);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.page-count {
  font-size: 12px;
  font-weight: 500;
  color: #909399;
  line-height: 1;
}

.divider {
  width: 1px;
  height: 12px;
  background: rgba(64, 158, 255, 0.3);
  margin: 0 2px;
}

.pagination-info {
  font-size: 12px;
  font-weight: 500;
  color: #409eff;
  letter-spacing: 0.5px;
  min-width: 24px;
  text-align: center;
  line-height: 1;
}

.pagination-icon {
  font-size: 12px;
  color: #409eff;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.pagination-icon.expanded {
  transform: rotate(180deg);
}

/* 表格容器 */
.table-container {
  overflow-x: auto;
}

/* 统一表头样式 */
.table-container :deep(.el-table__header-wrapper) th {
  font-size: 14px !important;
  font-weight: 500 !important;
  color: #606266 !important;
}

/* 统一表格内容字体大小 */
.table-container :deep(.el-table__body-wrapper) td {
  font-size: 14px !important;
}

/* 新版表名列样式 */
.table-name-cell-new {
  display: flex;
  flex-direction: column;
  gap: 6px;
  width: 100%;
}

.table-name-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  width: 100%;
}

.table-name-text {
  flex: 1;
  white-space: nowrap;
  font-size: 14px;
  font-weight: 400;
  color: #303133;
  line-height: 1.4;
}

.table-copy-btn {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  padding: 0;
  opacity: 0;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #909399 0%, #B1B3B8 100%);
  border: none;
}

.table-name-wrapper:hover .table-copy-btn {
  opacity: 1;
}

.table-copy-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.table-copy-btn:active {
  transform: scale(0.95);
}

.table-badges {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

/* 旧版表名列样式（保留用于兼容） */
.table-name-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 250px;
}

.table-name-container {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.table-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 400;
  color: #303133;
  font-size: 14px;
  flex: 1;
  min-width: 0;
}

.copy-btn {
  padding: 4px !important;
  min-height: auto !important;
  opacity: 0;
  transition: all 0.3s ease;
  color: #909399 !important;
  border-radius: 4px;
}

.table-name-container:hover .copy-btn {
  opacity: 1;
}

.copy-btn:hover {
  color: #409eff !important;
  background-color: rgba(64, 158, 255, 0.1) !important;
}

.table-badges {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.number-cell {
  font-family: 'Monaco', 'Consolas', monospace;
  font-weight: 400;
  font-size: 14px;
}

.increment-cell {
  font-family: 'Monaco', 'Consolas', monospace;
  font-weight: 400;
  font-size: 14px;
}

.increment-cell.positive { color: #67c23a; }
.increment-cell.negative { color: #f56c6c; }
.increment-cell.zero { color: #909399; }

/* 纯增量设计：增量显示样式 */
.increment-display {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
}

.increment-tag {
  font-size: 10px !important;
  height: 16px !important;
  line-height: 14px !important;
  padding: 0 4px !important;
  border-radius: 2px !important;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.time-cell {
  color: #909399;
  font-size: 14px;
}

.no-data {
  color: #c0c4cc;
  font-style: italic;
}

/* 分页区域 */
.pagination-section {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.pagination-section .el-pagination {
  display: flex;
  justify-content: center;
}

/* 分页折叠动画 */
.pagination-slide-enter-active,
.pagination-slide-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.pagination-slide-enter-from,
.pagination-slide-leave-to {
  opacity: 0;
  max-height: 0;
  overflow: hidden;
}

.pagination-slide-enter-to,
.pagination-slide-leave-from {
  opacity: 1;
  max-height: 80px;
}

/* 同步进度样式 */
.sync-progress {
  text-align: center;
  padding: 20px;
}

.sync-progress p {
  margin-top: 16px;
  color: #606266;
}

/* SQL查询生成器样式 */
.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 40px;
  color: #606266;
}

.query-table-info {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #9c27b0;
}

.query-table-info h4 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
}

.query-table-info p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.query-result {
  margin-bottom: 20px;
}

.query-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.query-header h4 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.query-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.query-textarea {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
}

.query-textarea :deep(.el-textarea__inner) {
  background: #f5f5f5;
  border: 1px solid #dcdfe6;
  font-family: inherit;
  font-size: inherit;
  line-height: 1.5;
}

.query-fields h4 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
}

.fields-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.field-tag {
  background: #ecf5ff;
  color: #409eff;
  border: 1px solid #b3d8ff;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
}

/* 字段列表样式 */
.fields-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  padding: 8px;
  background-color: var(--el-fill-color-blank);
}

.field-item {
  padding: 12px;
  margin-bottom: 8px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
  background-color: var(--el-bg-color);
  transition: all 0.2s ease;
}

.field-item:hover {
  border-color: var(--el-color-primary-light-7);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.field-item:last-child {
  margin-bottom: 0;
}

.field-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.field-name {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.field-name strong {
  color: var(--el-color-primary);
}

.field-details {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.field-type {
  font-weight: 500;
}

.field-default {
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.field-default code {
  background-color: var(--el-fill-color-light);
  padding: 2px 4px;
  border-radius: 3px;
  font-size: 11px;
}

.field-comment {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: var(--el-text-color-regular);
  font-style: italic;
  padding-left: 20px;
  border-left: 3px solid var(--el-border-color-light);
  margin-left: 8px;
}

/* 批量操作计数样式 */
.batch-count {
  margin-left: 4px;
  font-size: 12px;
  font-weight: 600;
  opacity: 0.8;
}

/* 工具栏按钮颜色优化 */
.btn-one-click {
  background: linear-gradient(135deg, #1976d2 0%, #2196f3 100%) !important;
  border: none !important;
  color: white !important;
  box-shadow: 0 3px 12px rgba(25, 118, 210, 0.3) !important;
  transition: all 0.3s ease !important;
}

.btn-one-click:hover {
  background: linear-gradient(135deg, #1565c0 0%, #1976d2 100%) !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 6px 16px rgba(25, 118, 210, 0.4) !important;
}

.btn-fetch-latest {
  background: linear-gradient(135deg, #00c853 0%, #4caf50 100%) !important;
  border: none !important;
  color: white !important;
  box-shadow: 0 3px 12px rgba(0, 200, 83, 0.3) !important;
  transition: all 0.3s ease !important;
}

.btn-fetch-latest:hover {
  background: linear-gradient(135deg, #00a143 0%, #388e3c 100%) !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 6px 16px rgba(0, 200, 83, 0.4) !important;
}

.btn-statistics {
  background: linear-gradient(135deg, #ff9800 0%, #ffc107 100%) !important;
  border: none !important;
  color: white !important;
  box-shadow: 0 3px 12px rgba(255, 152, 0, 0.3) !important;
  transition: all 0.3s ease !important;
}

.btn-statistics:hover {
  background: linear-gradient(135deg, #f57c00 0%, #ff9800 100%) !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 6px 16px rgba(255, 152, 0, 0.4) !important;
}

.btn-monitor {
  background: linear-gradient(135deg, #9c27b0 0%, #e91e63 100%) !important;
  border: none !important;
  color: white !important;
  box-shadow: 0 3px 12px rgba(156, 39, 176, 0.3) !important;
  transition: all 0.3s ease !important;
}

.btn-monitor:hover {
  background: linear-gradient(135deg, #7b1fa2 0%, #c2185b 100%) !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 6px 16px rgba(156, 39, 176, 0.4) !important;
}

.btn-schema {
  background: linear-gradient(135deg, #00bcd4 0%, #26c6da 100%) !important;
  border: none !important;
  color: white !important;
  box-shadow: 0 3px 12px rgba(0, 188, 212, 0.3) !important;
  transition: all 0.3s ease !important;
}

.btn-schema:hover {
  background: linear-gradient(135deg, #0097a7 0%, #00acc1 100%) !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 6px 16px rgba(0, 188, 212, 0.4) !important;
}

.btn-config {
  background: linear-gradient(135deg, #607d8b 0%, #78909c 100%) !important;
  border: none !important;
  color: white !important;
  box-shadow: 0 3px 12px rgba(96, 125, 139, 0.3) !important;
  transition: all 0.3s ease !important;
}

.btn-config:hover {
  background: linear-gradient(135deg, #455a64 0%, #546e7a 100%) !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 6px 16px rgba(96, 125, 139, 0.4) !important;
}

/* 工具栏按钮文字和图标调整 */
.toolbar .el-button .el-icon {
  margin-right: 6px;
  font-size: 14px;
}

.toolbar .el-button {
  font-weight: 500;
  letter-spacing: 0.5px;
  border-radius: 8px;
  padding: 10px 20px;
  font-size: 14px;
}

/* 工具栏整体样式优化 */
.toolbar {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 16px 24px;
  margin-bottom: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.toolbar .button-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

.toolbar .el-divider--vertical {
  height: 24px;
  margin: 0 16px;
  border-color: rgba(0, 0, 0, 0.1);
}

/* 表格行操作按钮颜色优化 */
.table-container .el-button--small {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  margin-right: 8px;
}

/* 表格操作按钮颜色优化 */
/* 操作按钮样式 - 统一风格 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
  white-space: nowrap;
  justify-content: flex-start;
  align-items: center;
  min-width: 200px;
}

.action-buttons .el-button {
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
  width: 32px;
  height: 32px;
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.action-buttons .el-button:hover {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.action-buttons .el-button:active {
  transform: translateY(0) scale(0.98);
}

.action-buttons .el-button--primary {
  background: linear-gradient(135deg, #409EFF 0%, #66B3FF 100%);
  border: none;
}

.action-buttons .el-button--success {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
  border: none;
}

.action-buttons .el-button--warning {
  background: linear-gradient(135deg, #E6A23C 0%, #F0C78A 100%);
  border: none;
}

.action-buttons .el-button--info {
  background: linear-gradient(135deg, #909399 0%, #B1B3B8 100%);
  border: none;
}

/* 下拉菜单项图标样式 */
.el-dropdown-menu__item .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

/* 监控状态开关样式 */
.el-switch.is-checked {
  --el-switch-on-color: #00c853;
}

.el-switch {
  --el-switch-off-color: #dcdfe6;
}

/* 对话框样式优化 */
.el-dialog {
  border-radius: 12px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(25, 118, 210, 0.1);
}

.el-dialog__header {
  background: linear-gradient(135deg, rgba(25, 118, 210, 0.05) 0%, rgba(33, 150, 243, 0.05) 100%);
  border-bottom: 1px solid rgba(25, 118, 210, 0.1);
  border-radius: 12px 12px 0 0;
}

/* 加载状态优化 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(5px);
}

/* 消息提示优化 */
.el-message--success {
  background: linear-gradient(135deg, #00c853 0%, #4caf50 100%);
  border: none;
  color: white;
  box-shadow: 0 4px 16px rgba(0, 200, 83, 0.3);
}

.el-message--error {
  background: linear-gradient(135deg, #f44336 0%, #e57373 100%);
  border: none;
  color: white;
  box-shadow: 0 4px 16px rgba(244, 67, 54, 0.3);
}

.el-message--warning {
  background: linear-gradient(135deg, #ff9800 0%, #ffc107 100%);
  border: none;
  color: white;
  box-shadow: 0 4px 16px rgba(255, 152, 0, 0.3);
}

/* 工具栏按钮组样式 */
.button-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.group-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  margin-right: 8px;
  white-space: nowrap;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.toolbar-left .el-divider--vertical {
  height: 24px;
  margin: 0;
}

/* 搜索和筛选区域样式 */
.search-section {
  margin-bottom: 24px;
}

.search-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  flex-shrink: 0;
}

.search-title .el-icon {
  color: #409eff;
}

.instance-selector-compact .el-tag {
  flex-shrink: 0;
}

.search-form {
  margin: 0;
}

.search-form-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20px;
}

.search-form-fields {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  flex: 1;
}

.search-form-fields .el-form-item {
  margin-bottom: 0;
}

.search-form-actions {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.search-btn,
.reset-btn,
.advanced-btn,
.quick-actions-btn {
  border-radius: 6px;
  font-weight: 500;
}

/* 高级筛选区域 */
.advanced-filter-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.advanced-filter-fields {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.advanced-filter-fields .el-form-item {
  margin-bottom: 0;
}

/* 高级筛选折叠动画 */
.advanced-filter-enter-active,
.advanced-filter-leave-active {
  transition: all 0.3s ease;
  max-height: 200px;
  overflow: hidden;
}

.advanced-filter-enter-from,
.advanced-filter-leave-to {
  opacity: 0;
  max-height: 0;
  margin-top: 0;
  padding-top: 0;
}

.advanced-filter-enter-to,
.advanced-filter-leave-from {
  opacity: 1;
  max-height: 200px;
  margin-top: 16px;
  padding-top: 16px;
}

/* 快捷操作区域 */
.quick-actions-section {
  margin-top: 16px;
  padding: 16px;
  border-top: 2px solid #409eff;
  border-radius: 8px;
}

.quick-actions-toolbar {
  display: flex;
  justify-content: flex-start;
}

.quick-actions-toolbar .toolbar-left {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.quick-actions-toolbar .button-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.quick-actions-toolbar .el-divider--vertical {
  height: 24px;
  margin: 0 8px;
  border-color: #e4e7ed;
}

.quick-actions-toolbar .el-button {
  border-radius: 6px;
  font-weight: 500;
}

/* 快捷操作折叠动画 */
.quick-actions-enter-active,
.quick-actions-leave-active {
  transition: all 0.3s ease;
  max-height: 300px;
  overflow: hidden;
}

.quick-actions-enter-from,
.quick-actions-leave-to {
  opacity: 0;
  max-height: 0;
  margin-top: 0;
  padding-top: 0;
}

.quick-actions-enter-to,
.quick-actions-leave-from {
  opacity: 1;
  max-height: 300px;
  margin-top: 16px;
  padding-top: 16px;
}

/* 表详情对话框统一样式 */
/* 表详情对话框已使用统一样式 */

/* 表名自动补全样式 */
.table-suggestion-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
}

.suggestion-content {
  flex: 1;
  min-width: 0;
}

.suggestion-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.suggestion-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 2px;
}

.suggestion-db {
  font-size: 11px;
  color: #409eff;
  background: #ecf5ff;
  padding: 2px 6px;
  border-radius: 3px;
  font-weight: 500;
}

.suggestion-comment {
  font-size: 12px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

/* 自动补全下拉框样式 */
:deep(.el-autocomplete-suggestion__wrap) {
  max-height: 400px;
}

:deep(.el-autocomplete-suggestion li) {
  line-height: 1.5;
  padding: 8px 12px;
}

:deep(.el-autocomplete-suggestion li:hover) {
  background-color: #f5f7fa;
}

/* 响应式处理 */
@media (max-width: 1400px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .search-form-content {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .search-form-fields {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form-actions {
    justify-content: center;
  }
  
  /* 实例选择器在小屏幕下自适应 */
  .search-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .instance-selector-compact {
    width: 100%;
  }
  
  .instance-selector-compact .el-select {
    width: 100% !important;
  }
  
  /* 快捷操作在小屏幕下自适应 */
  .quick-actions-toolbar .toolbar-left {
    flex-direction: column;
    align-items: stretch;
    width: 100%;
  }
  
  .quick-actions-toolbar .button-group {
    justify-content: center;
  }
  
  .quick-actions-toolbar .el-divider--vertical {
    display: none;
  }
  
  .filter-section {
    justify-content: center;
  }
}

/* 对话框样式 */
.dialog-content {
  padding: 20px 0;
}

.dialog-content .el-form-item {
  margin-bottom: 20px;
}

.selected-tables-info {
  margin-top: 16px;
}
</style>
